vim9script noclear

export def Highlight_Matching_Pair()
	var [c, c2, flags] = ['', '', '']
	var [idx, stopline, timeout] = [0, 0, 300]
	var c_lnum = line('.')
	var c_col = col('.')
	var stoplinebottom = line('w$')
	var stoplinetop = line('w0')
	var plist = ['(', ')', '{', '}', '[', ']']

	if !exists("w:matchparen_ids")
		w:matchparen_ids = []
		w:paren_hl_on = 0
	endif
	Remove_Matches()

	if pumvisible() || empty(&ft)
		return
	endif

	c = getline(c_lnum)->strpart(c_col - 1)->slice(0, 1)

	idx = index(plist, c)
	if idx < 0
		return
	endif

	if idx % 2 == 0
		flags = 'nW'
		c2 = plist[idx + 1]
		stopline = stoplinebottom
	else
		flags = 'nbW'
		c2 = c
		c = plist[idx - 1]
		stopline = stoplinetop
	endif

	if c == '['
		c = '\['
		c2 = '\]'
	endif

	if mode() == 'i' || mode() == 'R'
		timeout = 60
	endif

	var [m_lnum, m_col] = searchpairpos(c, '', c2, flags, '', stopline, timeout)
	if m_lnum > 0 && m_lnum >= stoplinetop && m_lnum <= stoplinebottom 
		add(w:matchparen_ids, matchaddpos('MatchParen', [[c_lnum, c_col], [m_lnum, m_col]], 10))
		w:paren_hl_on = 1
	endif
enddef

export def Remove_Matches()
	if w:paren_hl_on
		while !empty(w:matchparen_ids)
			silent! remove(w:matchparen_ids, 0)->matchdelete()
		endwhile
		w:paren_hl_on = 0
	endif
enddef
